<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
		<style>
			.active {
				color: red;
				font-size: 20px;
				background-color: orange;
			}
		</style>
	</head>
	<body>
		<ul>
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
			<li>5</li>
			<li>6</li>
			<li>7</li>
			<li>8</li>
			<li>9</li>
			<li>10</li>
		</ul>

		<script>
			/* var lisEl = document.querySelectorAll('li')
			lisEl.forEach(function (outerItem) {
				outerItem.addEventListener('click', function (e) {
					lisEl.forEach(function (item) {
						item.classList.remove('active')
					})

					this.classList.add('active')
				})
			}) */

			// 方式一: 排他操作
			/* var lisEl = document.querySelectorAll('li')
			function removeActive() {
				lisEl.forEach(function (liEl) {
					if (liEl.classList.contains('active')) {
						liEl.classList.remove('active')
					}
				})
			}

      // 方式二: 直接查找
			var ulEl = document.querySelector('ul')
			ulEl.addEventListener('click', function (e) {
				if (e.target.tagName === 'LI') {
					// removeActive()
					var activeLiEl = document.querySelector('ul li.active')
					activeLiEl?.classList?.remove('active')

					e.target.classList.add('active')
				}
			}) */

			// 方式三: 变量记录
			var ulEl = document.querySelector('ul')
			var activeLiEl = null
			ulEl.addEventListener('click', function (e) {
				if (activeLiEl) {
					activeLiEl.classList.remove('active')
				}
				if (e.target.tagName === 'LI') {
					e.target.classList.add('active')
					activeLiEl = e.target
				}
			})
		</script>
	</body>
</html>
